package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Autowired
    private StringRedisTemplate  stringRedisTemplate;

    @Override
    public Result queryList() {
        //1.查看缓存中是否有商品列表信息
        String shopType = stringRedisTemplate.opsForValue().get(RedisConstants.CACHE_SHOP_TYPE_KEY);
        if(StrUtil.isNotBlank(shopType)){
            //2.如果不为空则直接返回该数据
            List<ShopType> shopTypesList = JSONObject.parseArray(shopType, ShopType.class);
            return Result.ok(shopTypesList);
        }
        //3.如果为空则去数据库当中查询
        LambdaQueryWrapper<ShopType> qw = new LambdaQueryWrapper<>();
        qw.orderByDesc(ShopType::getSort);
        List<ShopType> list = super.list(qw);

        //4.写入到缓存当中,将list转换为json字符串，使用fastJson中的toJson方法
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_TYPE_KEY
                , JSON.toJSON(list).toString());
        return Result.ok(list);
    }
}
